package com.zndroid.netmonitor.monitor.impl;

import android.content.Context;
import android.net.ConnectivityManager;
import android.os.Build;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.zndroid.netmonitor.NetType;
import com.zndroid.netmonitor.monitor.INetChangeCallBack;

import java.lang.ref.WeakReference;

/**
 * API >=21 采用广播的形式实现
 * */
@RequiresApi(api = Build.VERSION_CODES.O)
public class MonitorImplAPI26 extends MonitorImplAPI21 {

    public MonitorImplAPI26(@NonNull INetChangeCallBack netChangeCallBack) {
        super(netChangeCallBack);
    }

    @Override
    public void startMonitor(@NonNull Context context) {
        if (isReg.get()) return;//防止重复调用

        Log.d(TAG, "MonitorImplAPI26 impl...");

        this.context = new WeakReference<>(context);

        if (!util.isNetworkAvailable(context))
            netChangeCallBack.onNetConnected(false, NetType.NET_NONE);

        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (manager != null)
            manager.registerDefaultNetworkCallback(this);
        else
            netChangeCallBack.onNetConnected(false, NetType.NET_NONE);


        monitorSignal(context);

        isReg.set(true);
    }

    @Override
    protected void monitorPhoneSignal(@NonNull Context context) {
        mPhoneStateListener = new PhoneStateListener() {
            @Override
            public void onSignalStrengthsChanged(SignalStrength signalStrength) {
                super.onSignalStrengthsChanged(signalStrength);
                if (util.getNetType(context).contentEquals(NetType.NET_WIFI)) return;

                netChangeCallBack.onNetChanged(util.isNetworkAvailable(context), util.getNetType(context), signalStrength.getLevel());
            }
        };


        if (util.hasSimCard(context)) {
            TelephonyManager telephonyManager = (TelephonyManager) this.context.get().getSystemService(Context.TELEPHONY_SERVICE);
            assert telephonyManager != null;
            telephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
        }
    }
}
